package TenkindsOfAlgorithm.divideAndConquer;

import java.util.Arrays;
import java.util.Collections;

/**
 * 主要分为二种方式 递归+非递归
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 8};
        Arrays.sort(arr);
        int i1 = binarySearchV2(arr, 8);
        System.out.println(i1);
        int i = binarySearchV1(arr, 0, arr.length, 8);
        System.out.println(i);
    }

    private static int counts = 0;

    /**
     * 使用递归的方式 i为要寻找的值
     */
    private static int binarySearchV1(int[] arr, int left, int right, int value) {
        counts++;
        int mid = left + (right - left) / 2;
        while (left <= right) {
            if (arr[mid] > value) {
                return binarySearchV1(arr, left, mid - 1, value);
            } else if (arr[mid] < value) {
                return binarySearchV1(arr, mid + 1, right, value);
            } else {
                return mid + 1;
            }
        }
        // left > right 未找到情况
        return -1;
    }

    /**
     * 使用非递归的方式
     */
    public static int binarySearchV2(int[] arr, int value) {
        if (value < arr[0] || value > arr[arr.length - 1]) {
            System.out.println("None exist");
            return -1;
        }
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] > value) {
                // 向左
                right = mid - 1;
            } else if (arr[mid] < value) {
                left = mid + 1;
            } else {
                return mid + 1;
            }
        }
        return -1;
    }
}
